package com.wuax.service.impl;

import cn.hutool.core.util.IdUtil;
import com.wuax.domain.Book;
import com.wuax.domain.Borrow;
import com.wuax.domain.vo.Result;
import com.wuax.mapper.BookMapper;
import com.wuax.mapper.BorrowMapper;
import com.wuax.service.BorrowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class BorrowServiceImpl implements BorrowService {

    @Autowired
    private BorrowMapper borrowMapper;

    @Autowired
    private BookMapper bookMapper;

    @Override
    public List<Borrow> select(Borrow borrow) {
        return borrowMapper.select(borrow);
    }

    @Override
    @Transactional
    public Result borrow(Borrow borrow) throws RuntimeException {
        // 生成uuid
        String uuid = IdUtil.simpleUUID();
        borrow.setBorrowId(uuid);
        // 初始化删除为未删除
        borrow.setIsDelete("0");
        // 插入借书记录
        int insert = borrowMapper.insert(borrow);
        if (insert == 1) {
            // 借出记录插入成功再修改图书借出状态为已借出
            Book book = new Book();
            book.setBookId(borrow.getBookId());
            book.setBorrowId(uuid);
            // 更新图书
            int update = bookMapper.update(book);
            if (update == 1) {
                return Result.success("借出成功");
            } else {
                // 抛出异常用于事务回滚，回滚借出记录
                throw new RuntimeException("借出失败");
            }
        }
        return Result.error("借出失败");
    }

    @Override
    @Transactional
    public Result returnBook(List<String> borrowIds) throws RuntimeException {
        for (String borrowId : borrowIds) {
            // 删除借书记录
            int delete = borrowMapper.delete(borrowId);
            if (delete != 1) {
                // 抛出异常用于事务回滚，防止其他图书被修改
                throw new RuntimeException("还书失败");
            }
            // 更新图书借出状态为未借出
            int update = bookMapper.borrowBook(borrowId);
            if (update != 1) {
                throw new RuntimeException("还书失败");
            }
        }
        return Result.success("还书成功");
    }
}
